package com.atwisdom.star.core.dsl.mqListener;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.UuidTool;
import com.atwisdom.star.common.vo.ActionData;
import com.atwisdom.star.redis.listener.AtWisdomMessageListener;
import com.atwisdom.star.redis.util.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
@Slf4j
public class ThirdMessageListener implements AtWisdomMessageListener<String> {
    private RedisUtil redisUtil;
    // private EntityRuntimeDslService entityRuntimeDslService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(ObjectRecord<String, String> message) {
        try {
            String value = message.getValue();
            JSONObject messageJson = JSON.parseObject(value);
            log.info("receive message ={}", message);
            // System.out.println(0/0);
            List<ActionData> actionDataList = messageJson.entrySet().stream().map((e -> {
                ActionData actionData = new ActionData<>();
                JSONArray valueList = JSON.parseArray(JSON.toJSONString(e.getValue()));
                if (CollectionUtil.isNotEmpty(valueList)) {
                    List<JSONObject> dataList = valueList.stream().map(v -> {
                        JSONObject entityData = new JSONObject();
                        entityData.put("className", e.getKey());
                        entityData.put("type", "entity");
                        entityData.put("name", UuidTool.getUUID32());
                        entityData.put("values", v);
                        entityData.put("instanceId", UuidTool.getUUID32());
                        return entityData;
                    }).collect(Collectors.toList());
                    actionData.setData(dataList);
                }
                return actionData;
            })).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(actionDataList)) {
                //todo: 添加监听后的业务
                // actionDataList.forEach(d-> entityRuntimeDslService.addBatchInstance(d.getData()));
            }
            redisUtil.delete(message.getStream(), message.getId());
            log.info("message [{}] has already been deleted ", message.getId());
        } catch (Exception e) {
            // 此处抛出异常，会造成监听失效，应该是报警
            log.error("ThirdMessageListener throw Exception ", e);
        }
    }
}